package sicnu.cs.aps.common.util;


import lombok.val;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static sicnu.cs.aps.common.Constants.*;


/**
 * @author CaiKe
 */
@Component
public class RequestUtil {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST = "127.0.0.1";
    private static final String SEPARATOR = ",";

    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static String getCurrentUrl() {
        return getCurrentRequest().getServletPath();
    }

    /**
     * 获取当前用户Id
     *
     * @return
     */
    public static Long getCurrentUserId() {
        val principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return "anonymousUser".equals(principal) ? -1 : Long.parseLong(principal);
    }

    /**
     * 获取当前用户角色信息
     *
     * @return
     */
    public static Set<String> getCurrentUserRole() {
        return SecurityContextHolder.getContext().getAuthentication()
                .getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toSet());
    }

    /**
     * 判断是否为学院账户
     *
     * @return bool
     */
    public static boolean isCurrentUserACollege() {
        return getCurrentUserRole().contains(ROLE_COLLEGE) || getCurrentUserRole().contains(ROLE_COLLEGE_SUB);
    }


    /**
     * 判断是否为子账户
     *
     * @return bool
     */
    public static boolean isCurrentUserAChild() {
        return getCurrentUserRole().contains(ROLE_COLLEGE_SUB) || getCurrentUserRole().contains(ROLE_UNIVERSITY_SUB);
    }


    /**
     * 判断是否为老师账户
     *
     * @return bool
     */
    public static boolean isCurrentUserATeacher() {
        return getCurrentUserRole().contains(ROLE_TEACHER);
    }


    /**
     * 判断是否为学生账户
     *
     * @return bool
     */
    public static boolean isCurrentUserAStu() {
        return getCurrentUserRole().contains(ROLE_STUDENT);
    }

    /**
     * 判断是否为学校账户
     *
     * @return bool
     */
    public static boolean isCurrentUserAUniversity() {
        return getCurrentUserRole().contains(ROLE_UNIVERSITY) || getCurrentUserRole().contains(ROLE_UNIVERSITY_SUB);
    }


    /**
     * 判断是否为学生或老师账户
     * @return bool
     */
    public static boolean isCurrentUserTeacherOrStu() {
        return getCurrentUserRole().contains(ROLE_TEACHER) || getCurrentUserRole().contains(ROLE_STUDENT);
    }

    public static Authentication getCurrentAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取请求的真实ip地址
     */
    public static String getIpAddress() {
        final HttpServletRequest request = getCurrentRequest();
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (LOCALHOST.equals(ipAddress)) {
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(SEPARATOR) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

}

